package com.yingxin.yxerp.module.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yxerp.module.organization.entity.User;
import com.yingxin.yxerp.module.organization.entity.UserRole;
import com.yingxin.yxerp.module.organization.mapper.UserRoleMapper;
import com.yingxin.yxerp.module.organization.service.IUserRoleService;
import com.yingxin.yxerp.module.permission.entity.Role;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户-角色 服务实现类
 * @author fanchao
 * @since 2021-05-10
 */

@Service
public class UserRoleServiceImpl
        extends ServiceImpl<UserRoleMapper, UserRole>
        implements IUserRoleService {

    /**
     * 根据 userId 查询
     */
    @Override
    public List<UserRole> listByUserId(String userId) {
        QueryWrapper<UserRole> qw = new QueryWrapper<>();
        qw.lambda().eq(UserRole::getUserId, userId);
        return list(qw);
    }


    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean deleteByUserId(User user) {
        UpdateWrapper<UserRole> uw = new UpdateWrapper<>();
        uw.lambda().eq(UserRole::getUserId, user.getId());
        return remove(uw);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void create(User user, Role role) {
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        save(userRole);
    }

}
